<?php

/**
 * user actions.
 *
 * @package    xists
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class userActions extends sfActions
{
  
  public function preExecute()
  {
    $this->dateFormat = sfConfig::get('app_date_format');
    $this->monthlyWiseFormat = sfConfig::get('app_monthly_wise_format');
    $this->currency   = sfConfig::get('app_currency');
  }
  
  public function executeRegister(sfWebRequest $request)
  {
    $this->form = new XistsUserForm();
  }
  
  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post'));
    $this->form = new XistsUserForm();
    $this->processFormRegister($request, $this->form);
    $this->setTemplate('register');
  }
  
  protected function processFormRegister(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    
    if ($form->isValid())
    {
      if (!XistsUserPeer::getByUsername($form->getValue('ref_username'))) {
        $this->getUser()->setFlash('error', sprintf('Reference user "%s" does not exist.', $form->getValue('ref_username')));
      } elseif (!($xistsUser = XistsUserPeer::getByUsername($form->getValue('place_under_username')))) {
        $this->getUser()->setFlash('error', sprintf('Place under user "%s" does not exist.', $form->getValue('place_under_username')));
      } elseif(!$xistsUser->hasPositionEmpty($form->getValue('join_position'))) {
        $this->getUser()->setFlash('error', sprintf('"%s" does not have empty "%s" position.', $form->getValue('place_under_username'), XistsUserPeer::$joinPostion[$form->getValue('join_position')]));
      } elseif(!($xistPlan = XistsPlanPeer::retrieveByPK($form->getValue('plan_id'))) || !($xistPlan->hasValidDeposit($form->getValue('deposit_amount'))) ) {
        $this->getUser()->setFlash('error', 'Please check investment plan deposit amount');
      } else {
        $user = $form->save();
  	  	$this->redirect('@success');
      }
    } else {
      $this->getUser()->setFlash('error', 'Please correct following red marked error(s).');
    }
  }

  public function executeIndex(sfWebRequest $request)
  {
    //$this->xists_user_list = XistsUserPeer::doSelect(new Criteria());
  }

  public function executeProfile(sfWebRequest $request)
  {
    $this->xistsUser = XistsUserPeer::retrieveByPk($this->getUser()->getAttribute('userId'));
    $this->forward404Unless($this->xistsUser);
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($xistsUser = XistsUserPeer::retrieveByPk($this->getUser()->getAttribute('userId')), sprintf('Object xists_user does not exist (%s).', $request->getParameter('id')));
    $this->form = $this->getProfileForm($xistsUser);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
    $this->forward404Unless($xists_user = XistsUserPeer::retrieveByPk($request->getParameter('id')), sprintf('Object xists_user does not exist (%s).', $request->getParameter('id')));
    $this->form = $this->getProfileForm($xists_user);
    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }
  
  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $user = $form->save();
	  if ($this->getUser()->isAuthenticated()) {
		$this->redirect('@profile');
	  } else {
		$this->redirect('@success');
	  }
    }
  }
  
  private function getProfileForm($xistsUser)
  {
    $form = new XistsUserForm($xistsUser);
    unset(
	  $form['username'], $form['passwd'], 
	  $form['email'], $form['join_position'],
	  $form['ref_username'], $form['place_under_username'],
	  $form['plan_id'], $form['deposit_amount']
	);
	
	return $form;
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($xists_user = XistsUserPeer::retrieveByPk($request->getParameter('id')), sprintf('Object xists_user does not exist (%s).', $request->getParameter('id')));
    $xists_user->delete();

    $this->redirect('user/index');
  }

  public function executeSuccess(sfWebRequest $request)
  {
  }

  public function executeLogin(sfWebRequest $request)
  {
    $this->form = new XistsLoginForm();

    if ($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('login'));
      if ($this->form->isValid()) {
		$usr = $this->form['username']->getValue();
		$pwd = $this->form['password']->getValue();
		
		$pwd = md5($pwd);

		$criteria = new Criteria();
		$criteria->add(XistsUserPeer::USERNAME, $usr);
		$criteria->add(XistsUserPeer::PASSWD, $pwd);

		$xistsUser = XistsUserPeer::doSelectOne($criteria);
		
		if ($xistsUser) {
			$this->getUser()->setFlash('msg', 'Login Successful.');
			$this->getUser()->setAuthenticated(true);
			$this->getUser()->addCredential('user');
			$this->getUser()->setAttribute('logged', true);
			$this->getUser()->setAttribute('username', $xistsUser->getUsername());
			$this->getUser()->setAttribute('userId', $xistsUser->getId());
			$this->redirect('@welcome');
		} else {
			$this->getUser()->setFlash('error', 'Invalid Login/Password.');
		}

      }
    }
    
  }

  public function executeWelcome(sfWebRequest $request)
  {
    $this->xistsUser = $this->getXistsUser();
  }
  
  public function executeChangePassword(sfWebRequest $request)
  {
    $this->form = new XistsChangePasswordForm();

    if ($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('change'));
      if ($this->form->isValid()) {
        $xistsUser = XistsUserPeer::retrieveByPK($this->getUser()->getAttribute('userId'));
        $cur = $this->form['current_password']->getValue();
		$new = $this->form['new_password']->getValue();
		$cnf = $this->form['confirm_password']->getValue();
		$pwd = md5($cnf);
		
	      if ($xistsUser->getPasswd() !== md5($cur)) {
	        $this->getUser()->setFlash('error', sprintf('Invalid current password'));
	      } elseif ($new !== $cnf) {
	        $this->getUser()->setFlash('error', sprintf('Password mismatch'));
	      } else {
		    $xistsUser->setPasswd($pwd);
		    $xistsUser->save();
		    $this->getUser()->setFlash('notice', 'Password change was successful.');
	      }
      } else {
        $this->getUser()->setFlash('error', 'Please correct following red marked error(s).');
      }
    } 
  }
  
  public function executeGenealogy(sfWebRequest $request)
  {
    $xistsUserBlank = XistsUserPeer::getBlankUser();
    $this->setLayout(false);
    $this->xistsUser = XistsUserPeer::getByUsername($request->getParameter('username'));
    if (!$this->xistsUser) {
      $this->getUser()->setFlash('error', "User '".$request->getParameter('username')."' does not exist.");
      $this->xistsUser = XistsUserPeer::retrieveByPK($this->getUser()->getAttribute('userId'));
    }
    $this->forward404Unless($this->xistsUser);
    
    // level 1
    $this->xistsUser_1_left = ($xistsUser = $this->xistsUser->getSibling('left'))? $xistsUser : $xistsUserBlank;
    $this->xistsUser_1_right = ($xistsUser = $this->xistsUser->getSibling('right'))? $xistsUser : $xistsUserBlank;
    
    // level 2
    $this->xistsUser_2_1_left = ($xistsUser = $this->xistsUser_1_left->getSibling('left'))? $xistsUser : $xistsUserBlank;
    $this->xistsUser_2_2_right = ($xistsUser = $this->xistsUser_1_left->getSibling('right'))? $xistsUser : $xistsUserBlank;
    $this->xistsUser_2_3_left = ($xistsUser = $this->xistsUser_1_right->getSibling('left'))? $xistsUser : $xistsUserBlank;
    $this->xistsUser_2_4_right = ($xistsUser = $this->xistsUser_1_right->getSibling('right'))? $xistsUser : $xistsUserBlank;
    
    // level 3
    $this->xistsUser_3_1_left = ($xistsUser = $this->xistsUser_2_1_left->getSibling('left'))? $xistsUser : $xistsUserBlank;
    $this->xistsUser_3_2_right = ($xistsUser = $this->xistsUser_2_1_left->getSibling('right'))? $xistsUser : $xistsUserBlank;
    
    $this->xistsUser_3_3_left = ($xistsUser = $this->xistsUser_2_2_right->getSibling('left'))? $xistsUser : $xistsUserBlank;
    $this->xistsUser_3_4_right = ($xistsUser = $this->xistsUser_2_2_right->getSibling('right'))? $xistsUser : $xistsUserBlank;
    
    $this->xistsUser_3_5_left = ($xistsUser = $this->xistsUser_2_3_left->getSibling('left'))? $xistsUser : $xistsUserBlank;
    $this->xistsUser_3_6_right = ($xistsUser = $this->xistsUser_2_3_left->getSibling('right'))? $xistsUser : $xistsUserBlank;
    
    $this->xistsUser_3_7_left = ($xistsUser = $this->xistsUser_2_4_right->getSibling('left'))? $xistsUser : $xistsUserBlank;
    $this->xistsUser_3_8_right = ($xistsUser = $this->xistsUser_2_4_right->getSibling('right'))? $xistsUser : $xistsUserBlank;
  }
  
  public function executeStatistics(sfWebRequest $request)
  {
    $xistsUser = XistsUserPeer::getByUsername($request->getParameter('username'));
    if (!$xistsUser) {
      $xistsUser = XistsUserPeer::retrieveByPK($this->getUser()->getAttribute('userId'));
    }
    $this->xistsUsers = $xistsUser->getFollowers();
  }
  
  public function executeMyReturns(sfWebRequest $request)
  {
    $this->xistsUser = $this->getXistsUser();
    $this->data = $this->xistsUser->getMyReturns();
  }
  
  public function executeReferelIncome(sfWebRequest $request)
  {
    $this->xistsUser = $this->getXistsUser();
    $this->data = $this->xistsUser->getReferelIncome();
  }
  
  public function executeMatchingIncome(sfWebRequest $request)
  {
    $this->xistsUser = $this->getXistsUser();
    $this->data = $this->xistsUser->getMatchingIncome();
  }
  
  public function executeTotalIncome(sfWebRequest $request)
  {
    $this->xistsUser = $this->getXistsUser();
    $this->data = $this->xistsUser->getTotalIncome();
  }
  
  public function executeLogout()
  {
    $this->getUser()->clearCredentials();
    $this->getUser()->setAuthenticated(false);
    $this->redirect('@homepage');
  }
  
  private function getUserId()
  {
    return $this->getUser()->getAttribute('userId');
  }
  
  private function getXistsUser()
  {
    return XistsUserPeer::retrieveByPK($this->getUserId());
  }

}
